﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using SaveCurrentState.Util;
using ManageWorkingState;

namespace SaveCurrentState
{
    public partial class MainForm : Form {
        #region constants
        private int COLUMN_CHECKBOX_INDEX = 3;
        private int HEADER_ROW_INDEX = -1;
        #endregion
        #region IFields

        private Color backColor_Normal;
        private Color backupTransparentKey;
        private Point lastPoint;
        private XmlResourceHelper m_xmlResourceHelper;
        private bool m_isShowed;
        private GridFileFolderItem itemBeforeEdit;
        private bool m_isDoubleClickCheckBox;
        private Point m_hiddenPosition;
        private Point m_normalPosition;


        #endregion

        #region constructors

        public MainForm()
        {
            m_xmlResourceHelper = new XmlResourceHelper();
            m_isShowed = true;
            itemBeforeEdit = new GridFileFolderItem();
            var listFile = m_xmlResourceHelper.GetAllRecordFromXml();
            m_hiddenPosition = m_xmlResourceHelper.GetPosition(Constants.HIDDEN_POSITION_NAME);
            m_normalPosition = m_xmlResourceHelper.GetPosition(Constants.NORMAL_POSITION_NAME);

            InitializeComponent();
            gridFileFolderItemBindingSource.DataSource = listFile;
        }

        #endregion

        #region Event Handlers

        private void toolStripbtOpenAll_Click(object sender, EventArgs e) {
            OpenAllItem();
        }

        private void toolStripbtAddFolder_Click(object sender, EventArgs e) {
            AddLocationUsingDialog();
        }


        private void toolStripbtAddFile_Click(object sender, EventArgs e) {
            AddFileUsingDialog();
        }

        private void toolStripBtAddFromWE_Click(object sender, EventArgs e) {
            var folderPaths = WindowExeplorerAndIEManage.GetInstance().GetWindowExplorerFilePath();
            if (dataGridFileFolder.Rows.Count > 0 &&
                MessageBox.Show("Clear all existing folder item in list ?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                DeleteAllItemsWithType(Constants.TYPE_FOLDER);
            }

            foreach (var folderPath in folderPaths) {
                AddNewFile(folderPath.FileName, folderPath.FilePath, Constants.TYPE_FOLDER);
            }
        }

        private void toolStripBtRemove_Click(object sender, EventArgs e) {
            DeleteItem();
        }

        private void toolStripbtShowHide_Click(object sender, EventArgs e) {
            HideForm();
        }

        private void toolStripbtExit_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void ContextMenuExit_Click(object sender, EventArgs e) {
           // m_xmlResourceHelper.SaveXmlData();
            this.Close();
        }

        private void showHideToolStripMenuItem_Click(object sender, EventArgs e) {
            showHideLstFileToolStripMenuItem.Checked = ContextMenuShowHide.Checked;
            if (ContextMenuShowHide.Checked) {
                ShowForm();
            } else {
                HideForm();
            }
        }

        private void OnDragDrop(object sender, DragEventArgs e) {
            this.Location = new Point(e.X, e.Y);
            this.DoDragDrop(this, DragDropEffects.Move);
        }

        private void MouseMoveEvent(object sender, MouseEventArgs e) {
            // Update position.
            if (e.Button == MouseButtons.Left && lastPoint != null) {
                this.Left += e.X - lastPoint.X;
                this.Top += e.Y - lastPoint.Y;
            }
        }

        private void MouseDownEvent(object sender, MouseEventArgs e) {
            lastPoint = new Point(e.X, e.Y);
        }

        private void MainForm_Load(object sender, EventArgs e) {
        }


        protected override void OnFormClosing(FormClosingEventArgs e) {
            m_xmlResourceHelper.SaveXmlData();
            base.OnFormClosing(e);
        }

        private void addFileToolStripMenuItem_Click(object sender, EventArgs e) {
            AddFileUsingDialog();
        }

        private void addLocationToolStripMenuItem_Click(object sender, EventArgs e) {
            AddLocationUsingDialog();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e) {
            DeleteItem();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e) {
            OpenSelectedFile();
        }

        private void imgReopenDoubleClick(object sender, EventArgs e) {
            if (m_isShowed) {
                HideForm();
                m_isShowed = false;
            } else {
                ShowForm();
                m_isShowed = true;
            }
        }

        private void ShowHideForm(object sender, EventArgs e) {
            if (m_isShowed) {
                HideForm();
                m_isShowed = false;
            } else {
                ShowForm();
                m_isShowed = true;
            }
        }

        private void lstFileKeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Return) {
                OpenSelectedFile();
            }
        }

        private void LstFileShowHideChange(object sender, EventArgs e) {
            ContextMenuShowHide.Checked = showHideLstFileToolStripMenuItem.Checked;
            if (showHideLstFileToolStripMenuItem.Checked) {
                ShowForm();
            } else {
                HideForm();
            }
        }

        private void openAllToolStripMenuItem_Click(object sender, EventArgs e) {
            OpenAllItem();
        }



        private void btLoadExplorer_Click(object sender, EventArgs e) {
            
        }

        /// <summary>
        /// Before edit, store old value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {
            itemBeforeEdit = (GridFileFolderItem)dataGridFileFolder.Rows[e.RowIndex].DataBoundItem;
        }

        /// <summary>
        /// Event used to store edit information of cell
        /// </summary>
        private void GridCellEndEdit(object sender, DataGridViewCellEventArgs e) {
            var fileFolderItem = (GridFileFolderItem)dataGridFileFolder.Rows[e.RowIndex].DataBoundItem;
            m_xmlResourceHelper.UpdateANode(itemBeforeEdit.Path, fileFolderItem.Name, fileFolderItem.Path, fileFolderItem.Type, fileFolderItem.AllowOpenDefault);
        }

        private void GridMouseDoubleClick(object sender, MouseEventArgs e) {
            var ht = dataGridFileFolder.HitTest(e.X, e.Y);

            if (ht.Type == DataGridViewHitTestType.None) {
                //clicked on grey area
                HideForm();
            } 
        }
        #endregion

        #region Methods

        private void HideForm() {

            m_isShowed = false;
            this.ShowInTaskbar = false;
            contextMenuShowInTaskBar.Checked = false;
            //m_normalPosition = this.Location;

            if (m_hiddenPosition.X != Constants.DEFAULT_POSITION_VALUE) {
                this.Location = m_hiddenPosition;
            }

           
            backColor_Normal = this.BackColor;
            backupTransparentKey = this.TransparencyKey;
            //this.BackColor = Color.Red;
            this.TransparencyKey = BackColor;
            this.FormBorderStyle = FormBorderStyle.None;
            SetBoolFields(false);
            
        }

        private void ShowForm() {
            this.ShowInTaskbar = true;
            contextMenuShowInTaskBar.Checked = true;
            m_isShowed = true;
            m_hiddenPosition = this.Location;
            m_xmlResourceHelper.SavePosition(Constants.HIDDEN_POSITION_NAME, this.Location);

            if (m_normalPosition.X != Constants.DEFAULT_POSITION_VALUE) {
                this.Location = m_normalPosition;
            }

            this.CenterToScreen();
            pictureWhenHide.Visible = false;
            this.BackColor = backColor_Normal;
            this.TransparencyKey = backupTransparentKey;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            SetBoolFields(true);
        }

        private void SetBoolFields(bool value) {
            pictureWhenHide.Visible = !value;
            //btAddToList.Visible = value;
            //btRemove.Visible = value;
            //btOpen.Visible = value;
            //btAddLocation.Visible = value;
            //btExit.Visible = value;
            //btHide.Visible = value;
            //btLoadExplorer.Visible = value;
            toolStrip1.Visible = value;
            dataGridFileFolder.Visible = value;
            ContextMenuShowHide.Checked = value;
        }
        /// <summary>
        /// Add file information to list and xml
        /// </summary>
        private void AddNewFile(string fileName, string FilePath, string type) {
            if (IsFileExistInList(FilePath)) {
                MessageBox.Show(string.Format("File {0} exists in list!", FilePath));
                return;
            }

            AddItemToList(fileName, FilePath, type, true);
            m_xmlResourceHelper.AddANode(fileName, FilePath, type, true);
        }

        private void AddItemToList(string fileName, string FilePath, string type, bool isOpenDefault) {
            gridFileFolderItemBindingSource.Add(new GridFileFolderItem {
                Name = fileName,
                Path = FilePath,
                Type = type,
                AllowOpenDefault = isOpenDefault
            });
        }

        private bool IsFileExistInList(string filePath) {
            for (int i = 0; i < gridFileFolderItemBindingSource.Count; i++) {
                if (((GridFileFolderItem) gridFileFolderItemBindingSource[i]).Path == filePath) {
                    return true;
                }
            }

            return false;
        }

        private void AddFileUsingDialog() {
            if (dlgOpenFile.ShowDialog() == DialogResult.OK) {
                AddNewFile(dlgOpenFile.SafeFileName, dlgOpenFile.FileName, Constants.TYPE_FILE );
            }
        }

        private void AddLocationUsingDialog() {
            if (dlgOpenFolder.ShowDialog() == DialogResult.OK) {
                var folderPath = dlgOpenFolder.SelectedPath;
                var folderName = GetFolderNameFromPath(dlgOpenFolder.SelectedPath);
                AddNewFile(folderName, folderPath, Constants.TYPE_FOLDER);
            }
        }

        /// <summary>
        /// Get folder name from path to folder
        /// </summary>
        private string GetFolderNameFromPath(string path) {
            if (!string.IsNullOrEmpty(path)) {
                var tmp = path.Split(new[]{ '\\' });
                if (tmp.Length > 0) {
                    return tmp[tmp.Length - 1];
                }
            }

            return path;
        }

        /// <summary>
        /// Delete selected item in list
        /// </summary>
        private void DeleteItem() {
            foreach (DataGridViewRow gridRow in dataGridFileFolder.SelectedRows) {
                var fileFolderItem = (GridFileFolderItem)gridRow.DataBoundItem;
                m_xmlResourceHelper.RemoveANode(fileFolderItem.Name, fileFolderItem.Path);
                dataGridFileFolder.Rows.RemoveAt(gridRow.Index);
            }
        }

        private void DeleteAllItemsWithType(string type) {
            for (int i = 0; i < dataGridFileFolder.Rows.Count; i++ ) {
                var fileFolderItem = (GridFileFolderItem)dataGridFileFolder.Rows[i].DataBoundItem;
                if (fileFolderItem.Type == type) {
                    m_xmlResourceHelper.RemoveANode(fileFolderItem.Name, fileFolderItem.Path);
                    dataGridFileFolder.Rows.RemoveAt(dataGridFileFolder.Rows[i].Index);
                    i--;
                }
            }
        }
        /// <summary>
        /// Open selected item in list
        /// </summary>
        private void OpenSelectedFile() {
            foreach (DataGridViewRow gridRow in dataGridFileFolder.SelectedRows) {
                var fileFolderItem = (GridFileFolderItem)gridRow.DataBoundItem;
                OpenFileWithErrorCheck(fileFolderItem.Path);
            }
        }

        /// <summary>
        /// Open all item, except item have check not open.
        /// </summary>
        private void OpenAllItem() {
            foreach (GridFileFolderItem item in gridFileFolderItemBindingSource) {
                if (item.AllowOpenDefault) {
                    OpenFileWithErrorCheck(item.Path);
                }
            }
        }


        private void OpenFileWithErrorCheck(string filePath){
            if (!OpenDocumentHelper.OpenDocument(filePath)) {
                MessageBox.Show("Failed to open file/folder: " + filePath);
            }
        }
        #endregion

        private void pictureWhenHide_Click(object sender, EventArgs e) {

        }

        private void lstFileDragDrop(object sender, DragEventArgs e) {
            DragDropEffects effects = DragDropEffects.None;
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (Directory.Exists(path)) {
                }
            }
            
        }

        private void modifyToolStripMenuItem_Click(object sender, EventArgs e) {

        }

        private void GridCellDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
            if (e.ColumnIndex != COLUMN_CHECKBOX_INDEX && e.RowIndex != HEADER_ROW_INDEX) {
                OpenSelectedFile();
            }
        }

        private void showInTaskBarToolStripMenuItem_Click(object sender, EventArgs e) {
            this.ShowInTaskbar = contextMenuShowInTaskBar.Checked;
        }

        

        

        

        

        
    }
}
